import { create } from 'zustand';
import type { Menu } from '@/types';
import * as menuApi from '@/api/menu';

interface MenuState {
  menus: Menu[];
  buttons: Array<{ name: string; permission: string }>;
  collapsed: boolean;
  setMenus: (menus: Menu[]) => void;
  setButtons: (buttons: Array<{ name: string; permission: string }>) => void;
  setCollapsed: (collapsed: boolean) => void;
  toggleCollapsed: () => void;
  fetchMenus: () => Promise<void>;
  fetchButtons: () => Promise<void>;
  hasButton: (buttonName: string) => boolean;
}

export const useMenuStore = create<MenuState>((set, get) => ({
  menus: [],
  buttons: [],
  collapsed: false,

  setMenus: (menus) => {
    set({ menus });
  },

  setButtons: (buttons) => {
    set({ buttons });
  },

  setCollapsed: (collapsed) => {
    set({ collapsed });
  },

  toggleCollapsed: () => {
    set((state) => ({ collapsed: !state.collapsed }));
  },

  fetchMenus: async () => {
    try {
      const response = await menuApi.getUserMenus();
      if (response.data.success) {
        set({ menus: response.data.data });
      }
    } catch (error) {
      console.error('Failed to fetch menus:', error);
    }
  },

  fetchButtons: async () => {
    try {
      const response = await menuApi.getUserButtons();
      if (response.data.success) {
        set({ buttons: response.data.data });
      }
    } catch (error) {
      console.error('Failed to fetch buttons:', error);
    }
  },

  hasButton: (buttonName) => {
    const { buttons } = get();
    return buttons.some((btn) => btn.name === buttonName);
  },
}));

